package com.fhao.lotterysystem.controller;

import com.fhao.lotterysystem.common.errorcode.ControllerErrorCodeConstants;
import com.fhao.lotterysystem.common.exception.ControllerException;
import com.fhao.lotterysystem.common.pojo.CommonResult;
import com.fhao.lotterysystem.controller.param.UserRegisterParam;
import com.fhao.lotterysystem.controller.result.UserRegisterResult;
import com.fhao.lotterysystem.service.UserService;
import com.fhao.lotterysystem.service.dto.UserRegisterDTO;
import com.fhao.lotterysystem.utils.JacksonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;



@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;
    
    /**
     * 用户注册
     * @param param 参数封装, 使用@RequestBody注解是为了将接收到的前端json对象转成后端java对象.
     * @return
     */
    @PostMapping("/register")
    public CommonResult<UserRegisterResult> userRegister(
            @Validated @RequestBody UserRegisterParam param) {
        // 日志打印
        logger.info("userRegister UserRegisterParam:{}", JacksonUtil.writeValueAsString(param));
        // 嗲用Service层服务进行访问
        UserRegisterDTO userRegisterDTO = userService.register(param);
        return CommonResult.success(convertToUserRegisterResult(userRegisterDTO));
    }

    private UserRegisterResult convertToUserRegisterResult(UserRegisterDTO userRegisterDTO) {
        UserRegisterResult result = new UserRegisterResult();
        //校验参数
        if(null == userRegisterDTO) {
            throw new ControllerException(ControllerErrorCodeConstants.REGISTER_ERROR);
        }
        //返回结果
        result.setUserId(userRegisterDTO.getUserId());
        return result;
    }
}























